﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CodeTier.BUL;
using Source.ViewModels;

namespace Source.Controllers
{
    public class CartController : Controller
    {
        //
        // GET: /Cart/

        public ActionResult Index()
        {                
            CartShop cart = (CartShop)Session[Common.key.Cart];
            return View(cart);
        }

        public RedirectToRouteResult addToCart(int MaSP, int txt_sl)
        {
            CartShop cart;
            if (Session[Common.key.Cart] == null)
            {
                cart = new CartShop();
                Session[Common.key.Cart] = cart;
            }

            cart = (CartShop)Session[Common.key.Cart];

            var result = (from c in cart.ds_cart
                            where c.sp.MaSP == MaSP
                            select c).ToList().SingleOrDefault();                
            if (result == null)
            {
                SanPhamBUS sp = SanPhamBUS.getByIdConvert(MaSP);
                cart.addItem(sp, txt_sl);
                Session[Common.key.Cart] = cart;
            }
            else
            {
                result.addSL(txt_sl);
            }

            return RedirectToAction("Index");
        }

        public RedirectToRouteResult removeToCart(int MaSP)
        {
            CartShop cart = (CartShop)Session[Common.key.Cart];
            CartLine result = (from c in cart.ds_cart
                          where c.sp.MaSP == MaSP
                          select c).ToList().SingleOrDefault();

            cart.removeItem(result);

            return RedirectToAction("Index");
        }

        public RedirectToRouteResult addQuantity(int MaSP,int SL)
        {
            CartShop cart = (CartShop)Session[Common.key.Cart];
            CartLine result = (from c in cart.ds_cart
                               where c.sp.MaSP == MaSP
                               select c).ToList().SingleOrDefault();
            result.addSL(SL);
            return RedirectToAction("Index");
        }
    }
}
